<template>
    <div class="home-view" :class="{ 'dark-mode': isDarkMode }">
      <!-- 顶部导航 -->
      <app-header
        :is-dark="isDarkMode"
        @toggle-theme="toggleTheme"
        @create-article="showCreateModal = true"
        @search-focus="handleSearchFocus"
      />
  
      <!-- 重新设计的内容区域 -->
      <main class="main-content">
        <!-- 左侧边栏 -->
        <aside class="sidebar">
          <div class="category-menu">
            <h3 class="menu-title">
              <i class="fas fa-th-large"></i>
              分类导航
            </h3>
            <div class="menu-items">
              <div 
                v-for="category in categories"
                :key="category.id"
                class="menu-item"
                :class="{ active: currentCategory === category.id }"
                @click="selectCategory(category.id)"
              >
                <i :class="category.icon"></i>
                <span>{{ category.name }}</span>
                <span class="item-count">{{ category.count }}</span>
              </div>
            </div>
          </div>
  
          <div class="tag-cloud">
            <h3 class="menu-title">
              <i class="fas fa-tags"></i>
              热门标签
            </h3>
            <div class="tag-list">
              <span 
                v-for="tag in popularTags" 
                :key="tag.id"
                class="tag"
                :class="{ active: selectedTags.includes(tag.id) }"
                @click="toggleTag(tag.id)"
              >
                {{ tag.name }}
                <span class="tag-count">{{ tag.count }}</span>
              </span>
            </div>
          </div>
          <!-- 热门标签后添加工具栏目 -->
  <div class="sidebar-section">
    <h2 class="section-title">
      <i class="fas fa-tools"></i>
      实用工具
    </h2>
    <div class="tools-list">
      <ToolCard
        title="ER图生成工具"
        description="快速生成数据库ER关系图，支持多种数据库"
        icon="fas fa-project-diagram"
        to="/ertools"
        status="new"
      />
      <!-- 后续可以继续添加其他工具 -->
    </div>
  </div>
        </aside>
  
        <!-- 主要文章区域 -->
        <div class="content-area">
          <!-- 筛选工具栏 -->
          <div class="filter-toolbar">
            <div class="view-options">
              <button 
                v-for="view in viewTypes"
                :key="view.type"
                class="view-btn"
                :class="{ active: currentView === view.type }"
                @click="currentView = view.type"
              >
                <i :class="view.icon"></i>
              </button>
            </div>
  
            <div class="sort-options">
              <el-dropdown @command="handleSort" trigger="click">
                <span class="sort-trigger">
                  {{ currentSort.label }}
                  <i class="el-icon-arrow-down"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item 
                    v-for="option in sortOptions"
                    :key="option.value"
                    :command="option.value"
                  >
                    <i :class="option.icon"></i>
                    {{ option.label }}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </div>
  
          <!-- 文章列表 -->
          <div class="article-list">
            <el-row :gutter="20">
              <el-col :span="24" v-for="article in articles.list" :key="article.id">
                <el-card class="article-card" shadow="hover" @click.native="goToDetail(article.id)">
                  <!-- 文章封面图 -->
                  <div class="article-cover-wrapper">
                    <img :src="article.coverUrl" class="article-cover" :alt="article.title">
                  </div>
                  
                  <!-- 文章底部信息 -->
                  <div class="article-footer">
                    <!-- 左侧：标题和描述 -->
                    <div class="article-info">
                      <h3 class="article-title" :title="article.title">{{ article.title }}</h3>
                      <p class="article-excerpt" :title="article.excerpt">{{ article.excerpt }}</p>
                      <!-- 分类和标签 -->
                      <div class="article-tags">
                        <el-tag size="small" type="success" v-if="article.categoryName">
                          {{ article.categoryName }}
                        </el-tag>
                        <template v-if="article.tags && article.tags.length">
                          <el-tag 
                            size="small" 
                            v-for="tag in article.tags" 
                            :key="tag.id"
                            style="margin-left: 5px;">
                            {{ tag.name }}
                          </el-tag>
                        </template>
                      </div>
                    </div>
                    
                    <!-- 右侧：统计信息 -->
                    <div class="article-stats">
                      <span class="meta-item">
                        <i class="el-icon-view"></i> {{ article.viewCount || 0 }}
                      </span>
                      <span class="meta-item">
                        <i class="el-icon-star-off"></i> {{ article.likeCount || 0 }}
                      </span>
                      <span class="meta-item">
                        <i class="el-icon-chat-dot-round"></i> {{ article.commentCount || 0 }}
                      </span>
                      <span class="meta-item">
                        <i class="el-icon-time"></i> {{ formatDate(article.createdAt) }}
                      </span>
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
  
            <!-- 分页 -->
            <div class="pagination" v-if="articles.total > 0">
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handlePageChange"
                :current-page="queryParams.pageNum"
                :page-sizes="[10, 20, 30, 50]"
                :page-size="queryParams.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="articles.total">
              </el-pagination>
            </div>
          </div>
        </div>
      </main>
  
      <!-- 浮动操作按钮 -->
      <floating-actions
        @create="showCreateModal = true"
      />
  
      <!-- 创建文章模态框 -->
      <create-modal
        :visible.sync="showCreateModal"
        @success="handleCreateSuccess"
      />
    </div>
  </template>
  
  <script>
  import AppHeader from '@/components/views/blog/common/AppHeader.vue'
  import FloatingActions from '@/components/views/blog/common/FloatingActions.vue'
  import SkeletonLoader from '@/components/views/blog/common/SkeletonLoader.vue'
  import ArticleCard from '@/components/views/blog/articles/ArticleCard.vue'
  import CreateModal from '@/components/views/blog/articles/CreateModal.vue'
  import axios from 'axios'
  import { Message } from 'element-ui'
  import ToolCard from './common/ToolCard.vue'
  import dayjs from 'dayjs'
  
  export default {
    name: 'BlogHomePage',
  
    components: {
      AppHeader,
      FloatingActions,
      SkeletonLoader,
      ArticleCard,
      CreateModal,
      ToolCard
    },
  
    data() {
      return {
        isDarkMode: false,
        isNavFixed: false,
        showCreateModal: false,
        loading: false,
        hasMore: true,
        currentPage: 1,
        
        // 视图控制
        currentView: 'grid',
        currentCategory: null,
        currentSort: { value: 'newest', label: '最新发布', icon: 'el-icon-time' },
        selectedTags: [],
  
        // 文章列表
        articles: {
          list: [],
          total: 0,
          pageNum: 1,
          pageSize: 10
        },
  
        // 分类数据
        categories: [],
  
        // 视图类型
        viewTypes: [
          { type: 'grid', icon: 'fas fa-th-large' },
          { type: 'list', icon: 'fas fa-list' }
        ],
  
        // 排序选项
        sortOptions: [
          { value: 'newest', label: '最新发布', icon: 'el-icon-time' },
          { value: 'hottest', label: '最多阅读', icon: 'el-icon-view' },
          { value: 'commented', label: '最多评论', icon: 'el-icon-chat-line-round' },
        ],
  
        // 标签选项
        popularTags: [
          { id: 1, name: 'JavaScript', count: 42 },
          { id: 2, name: 'Vue', count: 38 },
          { id: 3, name: 'React', count: 35 },
          { id: 4, name: 'Node.js', count: 30 },
          { id: 5, name: 'TypeScript', count: 28 },
          { id: 6, name: 'CSS', count: 25 },
        ],
        pageSize: 10,
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          categoryId: null,
          tagId: null,
          keyword: '',
          sortBy: 'latest'
        },
        total: 0,
        featuredArticles: [],
        latestArticles: [],
        hotTags: []
      }
    },
  
    created() {
      this.initTheme()
      this.loadHomeData()
      this.loadArticles()
    },
  
    mounted() {
      window.addEventListener('scroll', this.handleScroll)
    },
  
    beforeDestroy() {
      window.removeEventListener('scroll', this.handleScroll)
    },
  
    watch: {
      currentCategory() {
        this.resetList()
      },
      currentSort() {
        this.resetList()
      },
      selectedTags() {
        this.resetList()
      }
    },
  
    methods: {
      initTheme() {
        const darkMode = localStorage.getItem('darkMode') === 'true'
        this.isDarkMode = darkMode
        document.documentElement.classList.toggle('dark-mode', darkMode)
      },
  
      toggleTheme() {
        this.isDarkMode = !this.isDarkMode
        document.documentElement.classList.toggle('dark-mode', this.isDarkMode)
        localStorage.setItem('darkMode', this.isDarkMode)
      },
  
      handleScroll() {
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop
        this.isNavFixed = scrollTop > 80
      },
  
      async loadHomeData() {
        try {
          this.loading = true
          const response = await axios.get('/api/blog/home')
          if (response.data.code === 200) {
            const { featuredArticles, latestArticles, hotTags, categories } = response.data.data
            this.featuredArticles = featuredArticles
            this.latestArticles = latestArticles
            this.hotTags = hotTags
            this.categories = categories
          } else {
            Message.error(response.data.message || '加载数据失败')
          }
        } catch (error) {
          console.error('加载首页数据失败:', error)
          Message.error('加载数据失败')
        } finally {
          this.loading = false
        }
      },
  
      async loadArticles() {
        try {
          this.loading = true
          const response = await axios.get('/api/blog/articles', {
            params: this.queryParams
          })
          if (response.data.code === 200) {
            this.articles = response.data.data
          } else {
            Message.error(response.data.message || '加载文章列表失败')
          }
        } catch (error) {
          console.error('加载文章列表失败:', error)
          Message.error('加载文章列表失败')
        } finally {
          this.loading = false
        }
      },
  
      resetList() {
        this.articles = {
          list: [],
          total: 0,
          pageNum: 1,
          pageSize: 10
        }
        this.currentPage = 1
        this.hasMore = true
        this.loadArticles()
      },
  
      loadMore() {
        this.loadArticles()
      },
  
      selectCategory(categoryId) {
        this.currentCategory = categoryId
        this.queryParams.categoryId = categoryId
        this.queryParams.pageNum = 1
        this.loadArticles()
      },
  
      viewArticle(articleId) {
        this.$router.push(`/doc/blog/detail/${articleId}`)
      },
  
      handleLike(articleId) {
        const article = this.articles.list.find(a => a.id === articleId)
        if (article) {
          article.isLiked = !article.isLiked
          article.likes += article.isLiked ? 1 : -1
        }
      },
  
      handleShare(articleId) {
        this.$message.success('分享功能开发中...')
      },
  
      handleSearchFocus() {
        // 实现搜索框获焦点逻辑
      },
  
      handleCreateSuccess(article) {
        this.showCreateModal = false
        this.articles.list.unshift(article)
        this.$message.success('文章发布成功！')
      },
  
      toggleTag(tagId) {
        const index = this.selectedTags.indexOf(tagId)
        if (index > -1) {
          this.selectedTags.splice(index, 1)
        } else {
          this.selectedTags.push(tagId)
        }
        this.queryParams.tagId = tagId
        this.queryParams.pageNum = 1
        this.loadArticles()
      },
  
      handleSort(value) {
        const option = this.sortOptions.find(opt => opt.value === value)
        if (option) {
          this.currentSort = option
          this.queryParams.sortBy = value
          this.loadArticles()
        }
      },
  
      handleSearch(keyword) {
        this.queryParams.keyword = keyword
        this.queryParams.pageNum = 1
        this.loadArticles()
      },
  
      handlePageChange(page) {
        this.queryParams.pageNum = page
        this.loadArticles()
      },
  
      handleSizeChange(size) {
        this.queryParams.pageSize = size
        this.queryParams.pageNum = 1
        this.loadArticles()
      },
  
      formatDate(date) {
        if (!date) return '暂无日期';
        try {
            const d = new Date(date);
            if (isNaN(d.getTime())) return '暂无日期';
            const year = d.getFullYear();
            const month = String(d.getMonth() + 1).padStart(2, '0');
            const day = String(d.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        } catch (e) {
            return '暂无日期';
        }
      },
  
      goToDetail(id) {
        console.log(id)
        this.$router.push(`/doc/blog/blog-detail/${id}`)
      },
  
      handleCategoryChange(category) {
        this.currentCategory = category
        this.queryParams.categoryId = category.id
        this.queryParams.pageNum = 1
        this.loadArticles()
      },
  
      handleTagClick(tag) {
        this.queryParams.tagId = tag.id
        this.queryParams.pageNum = 1
        this.loadArticles()
      }
    }
  }
  </script>
  
  <style>
  .home-view {
    min-height: 100vh;
    background: #f5f5f5;
    transition: all 0.3s ease;
  }
  
  .main-content {
    max-width: 1440px;
    margin: 0 auto;
    padding: 80px 24px 24px;
    display: grid;
    grid-template-columns: 260px 1fr;
    gap: 24px;
  }
  
  /* 侧边栏样式 */
  .sidebar {
    position: sticky;
    top: 80px;
    height: calc(100vh - 100px);
    display: flex;
    flex-direction: column;
    gap: 24px;
  }
  
  .category-menu,
  .tag-cloud {
    background: var(--card-bg);
    border-radius: 12px;
    padding: 20px;
    box-shadow: var(--card-shadow);
  }
  
  .menu-title {
    font-size: 16px;
    font-weight: 500;
    margin: 0 0 16px;
    color: var(--text-primary);
    display: flex;
    align-items: center;
    gap: 8px;
  }
  
  .menu-items {
    display: flex;
    flex-direction: column;
    gap: 4px;
  }
  
  .menu-item {
    padding: 10px 12px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    gap: 12px;
    color: var(--text-secondary);
    cursor: pointer;
    transition: all 0.3s ease;
  }
  
  .menu-item:hover {
    background: var(--hover-bg);
    color: var(--primary-color);
  }
  
  .menu-item.active {
    background: var(--primary-light);
    color: var(--primary-color);
  }
  
  .item-count {
    margin-left: auto;
    font-size: 12px;
    color: var(--text-tertiary);
  }
  
  /* 标签云样式 */
  .tag-list {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .tag {
    padding: 6px 12px;
    border-radius: 16px;
    background: var(--tag-bg);
    color: var(--text-secondary);
    font-size: 13px;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    gap: 6px;
  }
  
  .tag:hover {
    background: var(--tag-hover-bg);
    color: var(--primary-color);
  }
  
  .tag.active {
    background: var(--primary-color);
    color: #fff;
  }
  
  .tag-count {
    font-size: 12px;
    opacity: 0.8;
  }
  
  /* 内容区域样式 */
  .content-area {
    background: var(--card-bg);
    border-radius: 12px;
    padding: 24px;
    box-shadow: var(--card-shadow);
  }
  
  .filter-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid var(--border-color);
  }
  
  .view-options {
    display: flex;
    gap: 8px;
  }
  
  .view-btn {
    width: 36px;
    height: 36px;
    border: none;
    border-radius: 8px;
    background: var(--btn-bg);
    color: var(--text-secondary);
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
  }
  
  .view-btn:hover {
    background: var(--btn-hover-bg);
    color: var(--primary-color);
  }
  
  .view-btn.active {
    background: var(--primary-light);
    color: var(--primary-color);
  }
  
  .sort-trigger {
    padding: 8px 16px;
    border-radius: 8px;
    background: var(--btn-bg);
    color: var(--text-secondary);
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 8px;
    transition: all 0.3s ease;
  }
  
  .sort-trigger:hover {
    background: var(--btn-hover-bg);
  }
  
  /* 文章网格样式 */
  .articles-grid {
    display: grid;
    gap: 24px;
    margin-bottom: 24px;
  }
  
  .articles-grid.grid {
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  }
  
  .articles-grid.list {
    grid-template-columns: 1fr;
  }
  
  .card-hover {
    transition: transform 0.3s ease, box-shadow 0.3s ease;
  }
  
  .card-hover:hover {
    transform: translateY(-4px);
    box-shadow: var(--card-hover-shadow);
  }
  
  /* 加载更多样式 */
  .load-more {
    text-align: center;
    padding-top: 24px;
  }
  
  .load-more-btn {
    padding: 10px 24px;
    font-size: 14px;
    border-radius: 20px;
    background: var(--btn-bg);
    border: none;
    color: var(--text-secondary);
    cursor: pointer;
    transition: all 0.3s ease;
    display: inline-flex;
    align-items: center;
    gap: 8px;
  }
  
  .load-more-btn:hover {
    background: var(--btn-hover-bg);
    color: var(--primary-color);
  }
  
  .no-more {
    color: var(--text-tertiary);
    font-size: 14px;
  }
  
  /* CSS 变量 - 明亮模式 */
  :root {
    --primary-color: #1890ff;
    --primary-light: rgba(24, 144, 255, 0.1);
    --text-primary: #1f1f1f;
    --text-secondary: #666;
    --text-tertiary: #999;
    --card-bg: #fff;
    --card-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    --card-hover-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
    --border-color: #f0f0f0;
    --hover-bg: rgba(0, 0, 0, 0.04);
    --btn-bg: #f5f5f5;
    --btn-hover-bg: #e8e8e8;
    --tag-bg: #f5f5f5;
    --tag-hover-bg: #e8e8e8;
  }
  
  /* CSS 变量 - 暗黑模式 */
  .dark-mode {
    --primary-color: #40a9ff;
    --primary-light: rgba(64, 169, 255, 0.1);
    --text-primary: #fff;
    --text-secondary: #b0b0b0;
    --text-tertiary: #666;
    --card-bg: #1f1f1f;
    --card-shadow: 0 2px 12px rgba(0, 0, 0, 0.2);
    --card-hover-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
    --border-color: #333;
    --hover-bg: rgba(255, 255, 255, 0.04);
    --btn-bg: #2f2f2f;
    --btn-hover-bg: #3f3f3f;
    --tag-bg: #2f2f2f;
    --tag-hover-bg: #3f3f3f;
  }
  
  /* 响应式设计 */
  @media (max-width: 1024px) {
    .main-content {
      grid-template-columns: 1fr;
    }
  
    .sidebar {
      position: static;
      height: auto;
    }
  }
  
  @media (max-width: 768px) {
    .main-content {
      padding: 60px 16px 16px;
    }
  
    .content-area {
      padding: 16px;
    }
  
    .articles-grid.grid {
      grid-template-columns: 1fr;
    }
  
    .filter-toolbar {
      flex-direction: column;
      gap: 16px;
    }
  }
 
  .tools-list {
  margin-top: 16px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 16px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-title i {
  color: var(--primary-color);
}
</style>